<template>
  <view class="refund-page">
    <!-- 商品信息 -->
    <view class="order-info" v-if="orderInfo && orderInfo.id">
      <view class="order-header">
        <text class="order-title">订单信息</text>
        <text class="order-number">订单号：{{ orderInfo.orderNumber }}</text>
      </view>
      <view class="goods-item">
        <image class="goods-image" :src="orderInfo.pic" mode="aspectFill"></image>
        <view class="goods-detail">
          <view class="goods-name">{{ orderInfo.prodName }}</view>
          <view class="goods-spec">{{ orderInfo.remark || '' }}</view>
          <view class="goods-price">
            <text class="price">￥{{ formatPrice(orderInfo.price) }}</text>
            <text class="num">x{{ orderInfo.num }}</text>
          </view>
        </view>
      </view>
      <view class="order-amount">
        <text class="label">实付金额：</text>
        <text class="amount">￥{{ formatPrice(orderInfo.actualTotal) }}</text>
      </view>
    </view>

    <!-- 退款申请信息 -->
    <view class="refund-info" v-if="serviceInfo && serviceInfo.id">
      <view class="info-header">
        <text class="info-title">退款申请</text>
        <text class="apply-time">申请时间：{{ serviceInfo.createTime || '' }}</text>
      </view>

      <view class="info-item">
        <text class="item-label">退款类型</text>
        <text class="item-value">{{ getApplyTypeText(serviceInfo.applyType) }}</text>
      </view>

      <view class="info-item">
        <text class="item-label">退款金额</text>
        <text class="item-value refund-amount">￥{{ formatPrice(serviceInfo.refundAmount) }}</text>
      </view>

      <view class="info-item">
        <text class="item-label">退货数量</text>
        <text class="item-value">{{ serviceInfo.goodsNum || 0 }}件</text>
      </view>

      <view class="info-item">
        <text class="item-label">退款原因</text>
        <text class="item-value reason">{{ serviceInfo.buyerMsg || '无' }}</text>
      </view>

      <view class="info-item" v-if="photoList.length > 0">
        <text class="item-label">退款凭证</text>
        <view class="photo-list">
          <image
              v-for="(photo, index) in photoList"
              :key="index"
              :src="photo"
              mode="aspectFill"
              class="photo-item"
              @click="previewImage(photo)"
          ></image>
        </view>
      </view>
    </view>

    <!-- 退款进度 -->
    <view class="progress-info" v-if="orderInfo && orderInfo.id">
      <view class="progress-header">
        <text class="progress-title">退款进度</text>
      </view>

      <view class="steps-container">
        <view class="step-item"
              v-for="(step, index) in refundSteps"
              :key="index"
              :class="{
                'completed': step.status === 'completed',
                'current': step.status === 'current',
                'failed': step.status === 'failed'
              }"
        >
          <view class="step-icon">
            <view class="icon-circle" v-if="step.status === 'pending'">
              <text class="step-number">{{ index + 1 }}</text>
            </view>
            <u-icon v-else-if="step.status === 'completed'" name="checkmark" color="#19be6b"
                    size="24"></u-icon>
            <u-icon v-else-if="step.status === 'current'" name="clock" color="#276aee"
                    size="24"></u-icon>
            <u-icon v-else-if="step.status === 'failed'" name="close" color="#fa3534"
                    size="24"></u-icon>
          </view>

          <view class="step-content">
            <text class="step-title">{{ step.title }}</text>
            <text class="step-desc" v-if="step.desc">{{ step.desc }}</text>
            <text class="step-time" v-if="step.time">{{ step.time }}</text>
          </view>

          <view class="step-line" v-if="index < refundSteps.length - 1"></view>
        </view>
      </view>

      <!-- 拒绝原因 -->
      <view class="reject-reason"
            v-if="(serviceInfo.refundSts === 3 || serviceInfo.officialReview === 3) && serviceInfo.sellerMsg">
        <view class="reason-header">
          <u-icon name="info-circle" color="#fa3534" size="20"></u-icon>
          <text class="reason-title">拒绝原因</text>
        </view>
        <text class="reason-content">{{ serviceInfo.sellerMsg }}</text>
      </view>
    </view>

    <!-- 底部按钮 商家通过/退货退款/且买家没有退回快递(无运单号expressNo),显示本按钮-->
    <view class="bottom-actions" v-if="showReturnButton && !serviceInfo.expressNo">
      <view class="action-button" @click="openReturnModal">
        <text class="button-text">寄回商品</text>
      </view>
    </view>

    <!-- 退货物流信息弹窗 -->
    <u-popup :show="showReturnModal" mode="bottom" :border-radius="20" @close="cancelReturn">
      <view class="popup-container">
        <view class="popup-header">
          <text class="popup-title">填写退货物流信息</text>
          <u-icon name="close" @click="cancelReturn" size="28" color="#666"></u-icon>
        </view>

        <view class="return-form">
          <view class="form-item">
            <text class="form-label">物流公司名称</text>
            <input class="form-input" v-model="returnForm.expressName"
                   placeholder="请输入物流公司名称"/>
          </view>

          <view class="form-item">
            <text class="form-label">物流单号</text>
            <input class="form-input" v-model="returnForm.expressNo" placeholder="请输入物流单号"/>
          </view>

          <!--          <view class="form-item">-->
          <!--            <text class="form-label">发货时间</text>-->
          <!--            <input class="form-input" v-model="returnForm.shipTimeDisplay" placeholder="当前时间" disabled />-->
          <!--          </view>-->
        </view>

        <view class="popup-buttons">
          <view class="btn-cancel" @click="cancelReturn">
            <text class="btn-text">取消</text>
          </view>
          <view class="btn-confirm" @click="submitReturnInfo">
            <text class="btn-text">确认提交</text>
          </view>
        </view>
      </view>
    </u-popup>
  </view>
</template>

<script>
export default {
  data() {
    return {
      orderId: "",//订单id
      orderInfo: {},//订单信息
      serviceInfo: {},//售后信息
      showReturnModal: false, // 退货弹窗显示状态
      returnForm: {
        expressName: '', // 物流公司名称
        expressNo: '', // 物流单号
        orderId: '', // 订单ID
        shipTime: '', // 发货时间
        // id:"",
        shipTimeDisplay: '' // 发货时间显示
      },
      returnRules: {
        expressName: [
          {required: true, message: '请输入物流公司名称', trigger: 'blur'}
        ],
        expressNo: [
          {required: true, message: '请输入物流单号', trigger: 'blur'}
        ]
      }
    }
  },
  onLoad(opt) {
    if (opt && opt.id) {
      this.orderId = opt.id
      this._getOrderDetail(opt.id)
      this._getServiceInfo(opt.id)
    }
  },
  computed: {
    // 解析图片列表
    photoList() {
      if (this.serviceInfo.photoFiles) {
        return this.serviceInfo.photoFiles.split(',').filter(url => url.trim())
      }
      return []
    },

    // 是否显示寄回商品按钮
    showReturnButton() {
      // 退款类型为"退货退款"(applyType === 2) 且 商家审核同意(refundSts === 2)
      return this.serviceInfo.applyType === 2 && this.serviceInfo.refundSts === 2
    },

    // 退款步骤
    refundSteps() {
      const sellerStatus = this.serviceInfo.refundSts || 1  // 商家审核状态
      const officialStatus = this.serviceInfo.officialReview || 1  // 官方审核状态

      const steps = [
        {
          title: '提交申请',
          desc: '买家提交退款申请',
          time: this.serviceInfo.createTime || '',
          status: 'completed'
        },
        {
          title: '商家审核',
          desc: this.getSellerStatusDesc(sellerStatus),
          time: this.serviceInfo.updateTime || '',
          status: this.getSellerStatusClass(sellerStatus)
        },
        {
          title: '官方审核',
          desc: this.getOfficialStatusDesc(officialStatus, sellerStatus),
          time: '',
          status: this.getOfficialStatusClass(officialStatus, sellerStatus)
        },
        {
          title: '审核通过',
          desc: '退款处理完成',
          time: '',
          status: this.getFinalStatusClass(sellerStatus, officialStatus)
        }
      ]

      return steps
    }
  },
  methods: {
    // 根据id查询订单详情
    _getOrderDetail(id) {
      let params = {id}
      this.$api.getOrderDetail(params).then(res => {
        if (res.success) {
          this.orderInfo = res.result
        }
      })
    },

    // 格式化价格
    formatPrice(v) {
      const n = Number(v || 0)
      return n.toFixed(2)
    },

    // 查询售后信息
    _getServiceInfo(id) {
      let params = {orderId: id}
      this.$api.getMssdOrderRefundList(params).then(res => {
        if (res.success) {
          if (res.result.records.length > 0) {
            this.serviceInfo = res.result.records[0] || {}
          }
        }
      })
    },

    // 获取申请类型文本
    getApplyTypeText(type) {
      const typeMap = {
        1: '仅退款',
        2: '退款退货'
      }
      return typeMap[type] || '未知'
    },

    // 预览图片
    previewImage(url) {
      uni.previewImage({
        urls: this.photoList,
        current: url
      })
    },

    // 获取商家审核状态描述
    getSellerStatusDesc(status) {
      const statusMap = {
        1: '商家审核中',
        2: '商家审核同意',
        3: '商家审核拒绝'
      }
      return statusMap[status] || '商家审核中'
    },

    // 获取商家审核状态样式
    getSellerStatusClass(status) {
      const statusMap = {
        1: 'current',    // 待审核
        2: 'completed',  // 同意
        3: 'failed'      // 拒绝
      }
      return statusMap[status] || 'current'
    },

    // 获取官方审核状态描述
    getOfficialStatusDesc(officialStatus, sellerStatus) {
      const isRefund = this.orderInfo.isRefund || 0

      // 如果商家审核还在进行中，官方审核等待
      if (sellerStatus === 1) {
        return '等待商家审核'
      }

      // 商家审核完成后（无论同意或拒绝），都会进入官方审核
      // 根据isRefund字段判断是否已经到官方审核阶段
      if (isRefund >= 2) {
        const statusMap = {
          1: '官方审核中',
          2: '官方审核同意',
          3: '官方审核拒绝'
        }
        return statusMap[officialStatus] || '官方审核中'
      } else {
        return '等待进入官方审核'
      }
    },

    // 获取官方审核状态样式
    getOfficialStatusClass(officialStatus, sellerStatus) {
      const isRefund = this.orderInfo.isRefund || 0

      // 如果商家审核还在进行中，官方审核为等待状态
      if (sellerStatus === 1) {
        return 'pending'
      }

      // 如果还未到官方审核阶段（isRefund < 2），显示为等待
      if (isRefund < 2) {
        return 'pending'
      }

      // 已进入官方审核阶段，根据officialStatus显示状态
      const statusMap = {
        1: 'current',    // 待审核
        2: 'completed',  // 同意
        3: 'failed'      // 拒绝
      }
      return statusMap[officialStatus] || 'current'
    },

    // 获取最终状态样式
    getFinalStatusClass(sellerStatus, officialStatus) {
      const isRefund = this.orderInfo.isRefund || 0

      // 只有当官方审核通过（officialStatus === 2）且流程完成（isRefund === 3）时，才显示为完成
      if (officialStatus === 2 && isRefund === 3) {
        return 'completed'
      }

      // 如果官方审核拒绝，最终状态为失败
      if (officialStatus === 3) {
        return 'failed'
      }

      // 其他情况都为等待状态
      return 'pending'
    },

    // 打开退货弹窗
    openReturnModal() {
      // console.log('寄回商品')
      // console.log('当前 serviceInfo:', this.serviceInfo)
      // console.log('显示按钮条件:', this.showReturnButton)
      // console.log('弹窗状态设置前:', this.showReturnModal)
      this.initReturnForm()
      this.showReturnModal = true
      // console.log('弹窗状态设置后:', this.showReturnModal)
      // 强制触发视图更新
      this.$forceUpdate()
    },

    // 初始化退货表单
    initReturnForm() {
      const now = new Date()
      const formatTime = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')} ${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}:${String(now.getSeconds()).padStart(2, '0')}`

      this.returnForm = {
        expressName: '',
        expressNo: '',
        orderId: this.orderId,
        shipTime: now.toISOString(),
        // id:'',
        shipTimeDisplay: formatTime
      }
    },

    // 提交退货物流信息
    submitReturnInfo() {
      // 简单验证
      if (!this.returnForm.expressName.trim()) {
        uni.showToast({
          title: '请输入物流公司名称',
          icon: 'none'
        })
        return
      }

      if (!this.returnForm.expressNo.trim()) {
        uni.showToast({
          title: '请输入物流单号',
          icon: 'none'
        })
        return
      }

      let params = {
        id: this.serviceInfo.id,
        expressName: this.returnForm.expressName,
        expressNo: this.returnForm.expressNo,
        orderId: this.returnForm.orderId,
        shipTime: this.returnForm.shipTime
      }
      this.$api.refundExpress(params).then(res => {
        if (res.success) {
          uni.showToast({
            title: '退货信息提交成功',
            icon: 'none'
          })
          this.showReturnModal = false
          this.resetReturnForm()
          this._getServiceInfo(this.orderId)
        } else {
          console.error('退货物流信息提交失败:', res)
        }
      })
      // console.log('提交退货物流信息:', {
      //   expressName: this.returnForm.expressName,
      //   expressNo: this.returnForm.expressNo,
      //   orderId: this.returnForm.orderId,
      //   shipTime: this.returnForm.shipTime
      // })

    },

    // 取消退货
    cancelReturn() {
      this.showReturnModal = false
      this.resetReturnForm()
    },

    // 重置退货表单
    resetReturnForm() {
      this.returnForm = {
        expressName: '',
        expressNo: '',
        orderId: '',
        shipTime: '',
        shipTimeDisplay: '',
        // id:""
      }
    }
  },
}
</script>

<style lang="scss" scoped>
.refund-page {
  background: #f5f5f5;
  min-height: 100vh;
  padding-bottom: 120rpx;
}

.order-info {
  background: #fff;
  margin: 20rpx 0;

  .order-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 30rpx 32rpx 20rpx;
    border-bottom: 1rpx solid #f0f2f5;

    .order-title {
      font-size: 32rpx;
      font-weight: 600;
      color: #1d2129;
    }

    .order-number {
      font-size: 24rpx;
      color: #86909c;
    }
  }

  .goods-item {
    display: flex;
    padding: 20rpx 32rpx;

    .goods-image {
      width: 120rpx;
      height: 120rpx;
      border-radius: 12rpx;
      margin-right: 20rpx;
    }

    .goods-detail {
      flex: 1;

      .goods-name {
        font-size: 28rpx;
        color: #1d2129;
        line-height: 1.4;
        margin-bottom: 8rpx;
      }

      .goods-spec {
        font-size: 24rpx;
        color: #86909c;
        margin-bottom: 12rpx;
      }

      .goods-price {
        display: flex;
        align-items: center;
        justify-content: space-between;

        .price {
          font-size: 28rpx;
          color: #ff3131;
          font-weight: 600;
        }

        .num {
          font-size: 24rpx;
          color: #86909c;
        }
      }
    }
  }

  .order-amount {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    padding: 20rpx 32rpx;
    border-top: 1rpx solid #f0f2f5;

    .label {
      font-size: 28rpx;
      color: #4e5969;
    }

    .amount {
      font-size: 32rpx;
      color: #ff3131;
      font-weight: 600;
      margin-left: 10rpx;
    }
  }
}

.refund-info {
  background: #fff;
  margin: 20rpx 0;

  .info-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 30rpx 32rpx 20rpx;
    border-bottom: 1rpx solid #f0f2f5;

    .info-title {
      font-size: 32rpx;
      font-weight: 600;
      color: #1d2129;
    }

    .apply-time {
      font-size: 24rpx;
      color: #86909c;
    }
  }

  .info-item {
    display: flex;
    align-items: flex-start;
    padding: 24rpx 32rpx;
    border-bottom: 1rpx solid #f8f9fa;

    &:last-child {
      border-bottom: none;
    }

    .item-label {
      width: 160rpx;
      font-size: 28rpx;
      color: #4e5969;
      flex-shrink: 0;
    }

    .item-value {
      flex: 1;
      font-size: 28rpx;
      color: #1d2129;

      &.refund-amount {
        color: #ff3131;
        font-weight: 600;
        font-size: 32rpx;
      }

      &.reason {
        line-height: 1.5;
      }
    }

    .photo-list {
      display: flex;
      flex-wrap: wrap;
      gap: 12rpx;

      .photo-item {
        width: 120rpx;
        height: 120rpx;
        border-radius: 8rpx;
        border: 1rpx solid #e5e6eb;
      }
    }
  }
}


.progress-info {
  background: #fff;
  margin: 20rpx 0;

  .progress-header {
    padding: 30rpx 32rpx 20rpx;
    border-bottom: 1rpx solid #f0f2f5;

    .progress-title {
      font-size: 32rpx;
      font-weight: 600;
      color: #1d2129;
    }
  }

  .steps-container {
    padding: 40rpx 32rpx;

    .step-item {
      position: relative;
      display: flex;
      align-items: flex-start;
      padding-bottom: 40rpx;

      &:last-child {
        padding-bottom: 0;

        .step-line {
          display: none;
        }
      }

      .step-icon {
        width: 48rpx;
        height: 48rpx;
        margin-right: 24rpx;
        flex-shrink: 0;
        display: flex;
        align-items: center;
        justify-content: center;

        .icon-circle {
          width: 48rpx;
          height: 48rpx;
          border-radius: 50%;
          background: #f0f2f5;
          display: flex;
          align-items: center;
          justify-content: center;

          .step-number {
            font-size: 24rpx;
            color: #86909c;
            font-weight: 500;
          }
        }
      }

      .step-content {
        flex: 1;

        .step-title {
          font-size: 30rpx;
          color: #1d2129;
          font-weight: 500;
          display: block;
          margin-bottom: 8rpx;
        }

        .step-desc {
          font-size: 26rpx;
          color: #86909c;
          display: block;
          margin-bottom: 6rpx;
        }

        .step-time {
          font-size: 24rpx;
          color: #c9cdd4;
          display: block;
        }
      }

      .step-line {
        position: absolute;
        left: 24rpx;
        top: 48rpx;
        bottom: 0;
        width: 2rpx;
        background: #f0f2f5;
      }

      // 已完成状态
      &.completed {
        .step-icon .icon-circle {
          background: #19be6b;

          .step-number {
            color: #fff;
          }
        }

        .step-content .step-title {
          color: #19be6b;
        }

        .step-line {
          background: #19be6b;
        }
      }

      // 当前状态
      &.current {
        .step-icon .icon-circle {
          background: #276aee;

          .step-number {
            color: #fff;
          }
        }

        .step-content .step-title {
          color: #276aee;
        }

        .step-content .step-desc {
          color: #276aee;
        }
      }

      // 失败状态
      &.failed {
        .step-icon .icon-circle {
          background: #fa3534;

          .step-number {
            color: #fff;
          }
        }

        .step-content .step-title {
          color: #fa3534;
        }

        .step-content .step-desc {
          color: #fa3534;
        }
      }
    }
  }

  .reject-reason {
    margin: 20rpx 32rpx;
    padding: 24rpx;
    background: #fff2f0;
    border: 1rpx solid #ffccc7;
    border-radius: 12rpx;

    .reason-header {
      display: flex;
      align-items: center;
      margin-bottom: 12rpx;

      .reason-title {
        font-size: 28rpx;
        color: #fa3534;
        font-weight: 500;
        margin-left: 8rpx;
      }
    }

    .reason-content {
      font-size: 26rpx;
      color: #fa3534;
      line-height: 1.5;
    }
  }
}

.bottom-actions {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 20rpx 32rpx;
  padding-bottom: calc(20rpx + constant(safe-area-inset-bottom));
  padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
  background: #fff;
  border-top: 1rpx solid #f0f2f5;

  .action-button {
    width: 100%;
    height: 88rpx;
    background: linear-gradient(135deg, #667eea 0%, #667eea 100%);
    border-radius: 12rpx;
    display: flex;
    align-items: center;
    justify-content: center;

    &:active {
      opacity: 0.8;
    }

    .button-text {
      font-size: 32rpx;
      color: #fff;
      font-weight: 600;
    }
  }
}

.popup-container {
  //width: 600rpx;
  background: #fff;
  border-radius: 20rpx;
  overflow: hidden;
}

.popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 40rpx 32rpx 20rpx;
  border-bottom: 1rpx solid #f0f2f5;

  .popup-title {
    font-size: 32rpx;
    font-weight: 600;
    color: #1d2129;
  }
}

.return-form {
  padding: 32rpx;

  .form-item {
    margin-bottom: 32rpx;

    &:last-child {
      margin-bottom: 0;
    }

    .form-label {
      display: block;
      font-size: 28rpx;
      color: #1d2129;
      font-weight: 500;
      margin-bottom: 12rpx;
    }

    .form-input {
      width: 100%;
      height: 80rpx;
      padding: 0 24rpx;
      font-size: 28rpx;
      color: #1d2129;
      background: #f7f8fa;
      border: 1rpx solid #e5e6eb;
      border-radius: 8rpx;
      box-sizing: border-box;

      &:focus {
        border-color: #276aee;
        background: #fff;
      }

      &:disabled {
        background: #f7f8fa;
        color: #86909c;
      }
    }
  }
}

.popup-buttons {
  display: flex;
  border-top: 1rpx solid #f0f2f5;

  .btn-cancel,
  .btn-confirm {
    flex: 1;
    height: 88rpx;
    display: flex;
    align-items: center;
    justify-content: center;

    &:active {
      opacity: 0.8;
    }

    .btn-text {
      font-size: 32rpx;
      font-weight: 500;
    }
  }

  .btn-cancel {
    border-right: 1rpx solid #f0f2f5;

    .btn-text {
      color: #86909c;
    }
  }

  .btn-confirm {
    .btn-text {
      color: #276aee;
    }
  }
}
</style>
